/**
 * The contents of this file are subject to the OpenMRS Public License
 * Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */
package org.openmrs.module.clinicalsummary.web.controller;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.api.context.Context;
import org.openmrs.module.clinicalsummary.FileUtils;
import org.openmrs.module.clinicalsummary.SummaryConstants;
import org.openmrs.web.WebConstants;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 */
@Controller
@RequestMapping("/module/clinicalsummary/summaryUpload")
public class SummaryUploadFormController {
	
	private static final Log log = LogFactory.getLog(SummaryUploadFormController.class);
	
	private static final int IV_SIZE = 16;
	
	@RequestMapping(method = RequestMethod.GET)
	public void preparePage(ModelMap map) {
		// if we need to display something
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public void uploadSummaries(@RequestParam(required = true, value = "password") String password,
	                            @RequestParam(required = true, value = "passphrase") String passphrase,
	                            @RequestParam(required = true, value = "secretFile") MultipartFile secretFile,
	                            @RequestParam(required = true, value = "summaries") MultipartFile returnedData,
	                            HttpServletRequest request) {
		
		HttpSession httpSession = request.getSession();
		if (Context.isAuthenticated())
			try {
				
				int interval = httpSession.getMaxInactiveInterval();
				httpSession.setMaxInactiveInterval(-1); // don't let the session expire
				
				byte[] iv = new byte[IV_SIZE];
				
				// sanity check
				if (secretFile == null || secretFile.isEmpty())
					throw new IOException("Unable to read secret file.");
				
				InputStream secretFileInputStream = secretFile.getInputStream();
				
				int ivSize = secretFileInputStream.read(iv);
				// make sure the iv is 16 byte
				if (ivSize != IV_SIZE)
					throw new IOException("Secret file is corrupted or invalid secret file are being used.");
				
				secretFileInputStream.close();
				
				// sanity check
				if (returnedData == null || returnedData.isEmpty())
					throw new IOException("Unable to read collection of summaries file.");
				
				InputStream summariesInputStream = returnedData.getInputStream();
				
				FileUtils.inflateSummaries(summariesInputStream, SummaryConstants.GENERATED_PDF_LOCATION, password,
				    passphrase, iv);
				FileUtils.loadIndexFile("summaryindex.sql");
				
				summariesInputStream.close();
				
				log.info("Processing summary files completed ...");
				
				httpSession.setMaxInactiveInterval(interval);
				
				String message = "Inflating collection of summary files completed successfully. Please check if files are decrypted succesfully.";
				httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, message);
			}
			catch (Exception e) {
				String message = "Inflating collection of summary files failed. Please check the log file to see the problem(s)";
				httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
				
				log.error("Inflating collection of summary files failed ...", e);
			}
	}
}
